package QueryService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;

import Node.TMultiplexedProtocol;

public class QueryClient {
	
	// Member variables
	private TSocket transport;
	private QueryService.Client QueryProto;
	
	/**
	 * Constructor for QueryClient object.
	 * 
	 * @param server
	 * @param serverPort
	 * @throws TTransportException
	 */
	public QueryClient(String server, int serverPort) throws TTransportException {
	
		// Setup transport layer
		transport = new TSocket(server, serverPort);
		
		// Initialize protocol: JSON, compact, binary, etc.
		TBinaryProtocol protocol = new TBinaryProtocol(transport);

		// Register service (service name must match service name registered on server)
		TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "QueryService");
		
		// Initialize Query service client object
		QueryProto = new QueryService.Client(mp);
	}
	
	/**
	 * Function to get the IMDB movie titles matching a keyword
	 * 
	 * @param word
	 * @param titlesMatching
	 * @param origin
	 * @param ttl
	 * @return
	 * @throws TException
	 */
	public List<String> getKeysContainingWord(String word, 
											  Map<Integer, String> titlesMatching, 
											  int origin, 
											  int ttl) throws TException {
		// List of strings to be returned
		List<String> matches = new ArrayList<String>();
		
		transport.open();
		matches = QueryProto.getKeysContainingWord(word, titlesMatching, origin, ttl);
		transport.close();
		
		// Return the list of titles that match the word
		return matches;
	}
}
